• 直接上代码 ,三个类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import rx.Observable;
import rx.functions.Func1;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
* @author xzj
* @date 2016/8/24 14:00.
*/
public class RxBus {
private static RxBus mRxBus = null;
/**
* PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者
*/

private Subject<Object, Object> mRxBusObserverable = new SerializedSubject<>(PublishSubject.create());

public static synchronized RxBus getInstance() {
if (mRxBus == null) {
mRxBus = new RxBus();
}
return mRxBus;
}

public void send(Object o, String tag) {
mRxBusObserverable.onNext(new RxBusObject(tag, o));
}

// public Observable<Object> toObserverable() {
// return mRxBusObserverable;
// }

public <T> Observable<T> toObservable(final Class<T> eventType, final String tag) {
return mRxBusObserverable.filter(new Func1<Object, Boolean>() {
@Override
public Boolean call(Object o) {
if (!(o instanceof RxBusObject)) return false;
RxBusObject ro = (RxBusObject) o;
return eventType.isInstance(ro.getObj()) && tag != null
&& tag.equals(ro.getTag());
}
}).map(new Func1<Object, T>() {
@Override
public T call(Object o) {
RxBusObject ro = (RxBusObject) o;
return (T) ro.getObj();
}
});
}

/**
* 判断是否有订阅者
*/
public boolean hasObservers() {
return mRxBusObserverable.hasObservers();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

/**
* @author xzj
* @date 2016/8/24 14:22.
*/
public class RxBusObject {
private String tag;
private Object obj;

public RxBusObject(String tag, Object obj) {
this.tag = tag;
this.obj = obj;
}

public String getTag() {
return tag;
}

public void setTag(String tag) {
this.tag = tag;
}

public Object getObj() {
return obj;
}

public void setObj(Object obj) {
this.obj = obj;
}

public static RxBusObject newInstance(String tag, Object obj) {
return new RxBusObject(tag, obj);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

/**
* @author xzj
* @date 2016/8/24 14:24.
*/

import rx.Subscriber;

/**
* 请使用此类来subscribe RxBus返回的Observable以简化onError与onCompleted函数.
*/
public abstract class RxBusSubscriber<T> extends Subscriber<T> {
@Override
public void onCompleted() {
completed();
}

@Override
public void onError(Throwable e) {
error(e);
}

@Override
public void onNext(T t) {
receive(t);
}

public abstract void receive(T data);
public void error(Throwable e) {
e.printStackTrace();
}
public void completed() {}

}


  • 用法

Paste_Image.png
一个简单的例子
就是上下两个fragment,change按钮是在fragment里的,点击随机生成一个color发给下面的fragment2,下面的fragmeng2收到了,更改背景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_fragment, null);
Button btn = (Button) view.findViewById(R.id.btn);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Random random = new Random();
int color = Color.argb(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256));
RxBus.getInstance().send(color,"color");
}
});
return view;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
public class MyFragment2 extends Fragment {

private Subscription subscribe;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.layout_fragment2, null);
//标记发过来的是个int,tag是“color”,和被观测者send()方法里参数能匹配上,才会被这里观测到
subscribe = RxBus.getInstance().toObservable(Integer.class, "color")
.subscribe(new RxBusSubscriber<Integer>() {
@Override
public void receive(Integer data) {
view.setBackgroundColor(data);
}
});
return view;
}

@Override
public void onDestroyView() {
super.onDestroyView();
if (!subscribe.isUnsubscribed()) {
subscribe.unsubscribe();
}
}
}
~~~java
public static void init(Context context) {
sharedPreferences = context.getSharedPreferences("shared_files",
Context.MODE_PRIVATE);
gson = new Gson();
}

private static void checkInit() {
if (sharedPreferences == null || gson == null) {
throw new IllegalStateException("Please call init(context) first.");
}
}

/**
* 保存对象数据至SharedPreferences, key默认为类名, 如
* <pre>
* PreferencesHelper.putData(saveUser);
* </pre>
* @param data 不带泛型的任意数据类型实例
*/
public static <T> void putData(T data) {
putData(data.getClass().getName(), data);
}

/**
* 根据key保存对象数据至SharedPreferences, 如
* <pre>
* PreferencesHelper.putData(key, saveUser);
* </pre>
* @param data 不带泛型的任意数据类型实例
*/
public static <T> void putData(String key, T data) {
checkInit();
if (data == null)
throw new IllegalStateException("data should not be null.");
sharedPreferences.edit().putString(key, gson.toJson(data)).apply();
}

/**
* 保存List集合数据至SharedPreferences, 请确保List至少含有一个元素, 如
* <pre>
* PreferencesHelper.putData(users);
* </pre>
* @param data List类型实例
*/
public static <T> void putData(List<T> data) {
checkInit();
if (data == null || data.size() <= 0)
throw new IllegalStateException(
"List should not be null or at least contains one element.");
Class returnType = data.get(0).getClass();
sharedPreferences.edit().putString(returnType.getName() + LIST_TAG,
gson.toJson(data)).apply();
}

/**
* 将数据从SharedPreferences中取出, key默认为类名, 如
* <pre>
* User user = PreferencesHelper.getData(key, User.class)
* </pre>
*/
public static <T> T getData(Class<T> clz) {
return getData(clz.getName(), clz);
}

/**
* 根据key将数据从SharedPreferences中取出, 如
* <pre>
* User user = PreferencesHelper.getData(User.class)
* </pre>
*/
public static <T> T getData(String key, Class<T> clz) {
checkInit();
String json = sharedPreferences.getString(key, "");
return gson.fromJson(json, clz);
}

/**
* 将数据从SharedPreferences中取出, 如
* <pre>List<User> users = PreferencesHelper.getData(List.class, User.class)</pre>
*/
public static <T> List<T> getData(Class<List> clz, Class<T> gClz) {
checkInit();
String json = sharedPreferences.getString(gClz.getName() + LIST_TAG, "");
return gson.fromJson(json, new TypeToken<List>(){}.getType());
}

/**
* 简易字符串保存, 仅支持字符串
*/
public static void putString(String key, String data) {
sharedPreferences.edit().putString(key, data).apply();
}

/**
* 简易字符串获取, 仅支持字符串
*/
public static String getString(String key) {
return sharedPreferences.getString(key, "");
}

public static void putInt(String key, int data) {
sharedPreferences.edit().putInt(key,data).apply();
}

public static int getInt(String key) {
return sharedPreferences.getInt(key, -1);
}

public static void putBoolean(String key, boolean data) {
sharedPreferences.edit().putBoolean(key,data).apply();
}

public static boolean getBoolean(String key,boolean defaultData) {
return sharedPreferences.getBoolean(key, defaultData);
}

public static void putFloat(String key, float data) {
sharedPreferences.edit().putFloat(key,data).apply();
}

public static float getFloat(String key,float defaultData) {
return sharedPreferences.getFloat(key, defaultData);
}

public static void putLong(String key, long data) {
sharedPreferences.edit().putLong(key,data).apply();
}

public static float getLong(String key,long defaultData) {
return sharedPreferences.getLong(key, defaultData);
}

public static void clear() {
sharedPreferences.edit().clear().apply();
}

/**
* 删除保存的对象
*/
public static void remove(String key) {
sharedPreferences.edit().remove(key).apply();
}

/**
* 删除保存的对象
*/
public static void remove(Class clz) {
remove(clz.getName());
}

/**
* 删除保存的数组
*/
public static void removeList(Class clz) {
sharedPreferences.edit().remove(clz.getName() + LIST_TAG).apply();
}
}